import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { StockoutService } from '../../../service/order/stockout.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
  selector: 'report-stockoutsku',
  templateUrl: './stockoutsku.component.html',
})
export class ReportStockoutskuComponent implements OnInit, OnDestroy {
  inter;
  syncing = false;
  lastDate = null
  checkedList = [];

  ps = 10;
  q: any = {    
    sap: null      
  };  
  url = this.stockoutSku.list();
  data = [];
  columns: SimpleTableColumn[] = [    
    { title: '', index: 'key', type: 'checkbox' },
    { title: 'SAP', index: 'sap' },    
    { title: '订单数量', index: 'qty'},        
    { title: '库存', index: 'stock' },
    { title: '缺额', index: 'ed', render: 'ed' }
  ];
  @ViewChild('st') st: SimpleTableComponent;
  

  constructor(
    private stockoutSku: StockoutService, 
    private modal: ModalHelper
  ) { }

  ngOnInit() {    
    // 每隔5s获取同步状态
    this.inter = setInterval(() => {
      this.stockoutSku.getStockoutSkuStatus().pipe(catchError(err => {
        return of(err)
      })).subscribe(data => {
        if (data.status === 200) {          
          if (data.data) {
            let flag = false;
            if (data.data.last_date) {
              if (this.lastDate != null && this.lastDate != data.data.last_date) {
                flag = true;
              }
              this.lastDate = data.data.last_date;
            }
            if (data.data.status === 1) {
              this.syncing = true;              
            } else {
              if (flag) {
                this.st.load(1);
              }
              this.syncing = false;            
            }
          } else {
            this.syncing = false;
          }         
        } else {
          this.syncing = false;
        }
      })
    }, 2000);
  }

  ngOnDestroy() {
    if (this.inter) {
      clearInterval(this.inter);
    }
  }

  syncStock() {
    this.stockoutSku.doStockoutsku().pipe(catchError(err => {
      return of(err)
    })).subscribe(data => {      
        this.syncing = true;      
    })
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  getData(page = 1) {
    this.stockoutSku.page(page, 10).pipe(catchError(err => {
      return of(err)
    })).subscribe(data => {
      this.data = data.data.rows;
    })
  }

  export() {
    let param = `?pageNumber=1&pageSize=0`; 
    this.st.export(this.url + param, { filename: 'stockout.xlsx' });
  }
  
}
